<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Log;

/**
 * 后台菜单（权限）
 */
class Menu extends AdminBase
{
    protected $auth_rule_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->auth_rule_model = model('AuthRule');

        $where = [
            'order_str' => 'sort DESC,id ASC',
        ];

        $admin_menu_list            = $this->auth_rule_model->getList($where, 1000);
        $admin_menu_level_list      = array2level($admin_menu_list['data']);

        $this->assign('admin_menu_level_list', $admin_menu_level_list);
    }


    /**
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }
    /**
     * @return mixed
     */
    public function cate()
    {
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function add()
    {
        //父级菜单id
        $pid = $this->request->param('pid', 0, 'intval');

        if ($this->request->isAjax()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Menu');

            if ($validate_result !== true) {
                return ajax_return_error($validate_result);
            } else {
                //检查是否存在同名菜单
                if ($this->auth_rule_model->checkTitleExists($data['title']) || $this->auth_rule_model->checkNameExists($data['name'])) {
                    return ajax_return_error('菜单已存在！');
                }

                if ($this->auth_rule_model->addData($data)) {
                    return ajax_return_adv('保存成功');
                } else {
                    return ajax_return_error('保存失败');
                }
            }
        }

        return $this->fetch('add', [
            'pid' => $pid
        ]);
    }

    /**
     * 删除菜单
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        $sub_menu = $this->auth_rule_model->where(['pid' => $id])->find();
        if (!empty($sub_menu)) {
            return ajax_return_error('此菜单下存在子菜单，不可删除');
        }
        if ($this->auth_rule_model->destroy($id)) {
            return ajax_return_adv('删除成功');
        } else {
            return ajax_return_error('删除失败');
        }
    }
    /**
     * 删除菜单
     */
    public function deleteAll()
    {
        $ids = $this->request->param('ids', '', 'trim');
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter(array_map(function($v){
            return (int)$v;
        }, $ids)));

        foreach ($ids as $id) {
            $sub_menu = $this->auth_rule_model->field('id')->where(['pid' => $id])->find();
            if (!empty($sub_menu)) {
                $title = $this->auth_rule_model->field('title')->where(['id' => $id])->find();
                return ajax_return_error('菜单（'.$title['title'].'）下存在子菜单，不可删除');
            }

            if (!$this->auth_rule_model->destroy($id)) {
                return ajax_return_error('菜单（'.$sub_menu['title'].'）删除失败');
            }
        }
        return ajax_return_adv('删除成功');
    }

    /**
     * @return mixed
     */
    public function edit()
    {
        //父级菜单id
        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error('请指定要修改的记录！');
        }

        if ($this->request->isAjax()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Menu');

            if ($validate_result !== true) {
                return ajax_return_error($validate_result);
            } else {
                $old_info = $this->auth_rule_model->field('title,name')->where(['id' => $id])->find();
                if (empty($old_info)) {
                    return ajax_return_error('数据不存在，或已被删除');
                }

                $check_info = $this->auth_rule_model->checkTitleExists($data['title'], true);
                if (empty($check_info)) {
                    $check_info = $this->auth_rule_model->checkNameExists($data['name'], true);
                }
                if (!empty($check_info) && $check_info['id'] != $id) {
                    return ajax_return_error('该菜单已经存在，请重新填写');
                }

                if ($this->auth_rule_model->saveDate($id, $data) !== false) {
                    return ajax_return_adv('更新成功');
                } else {
                    return ajax_return_error('更新失败');
                }
            }
        }

        //获取到该记录的信息
        $rule_info = $this->auth_rule_model->where(['id' => $id])->find();
        return $this->fetch('edit', [
            'rule_info' => $rule_info
        ]);
    }
}
